package fractal.app;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;

/** Class make configuration application */
public class AppConfig {

	private String fileName;
	private Map<String, String> config;

	/** private constructor */
	private AppConfig() {
		this.fileName = AppDefine.CONFIGFILE;
		this.config = new HashMap<String, String>();
	}

	/** singleton class */
	private static class SingletonHolder {
		private final static AppConfig instance = new AppConfig();
	}

	/** method get instance class */
	public static AppConfig getInstance() {
		return SingletonHolder.instance;
	}

	/** method check key in hash map */
	public boolean has(String key) {
		return this.config.containsKey(key);
	}

	/** method set key and value */
	public boolean set(String key, String val) {
		if (this.config.containsKey(key)) {
			this.config.remove(key);
		}
		this.config.put(key, val);
		return this.has(key);
	}

	/** method get value as string */
	public String get(String key) {
		if (this.config.containsKey(key)) {
			return this.config.get(key);
		}
		return "";
	}

	/** method get value as integer */
	public int getInt(String key) {
		try {
			if (this.config.containsKey(key)) {
				String num = this.get(key);

				if (num.length() > 0) {
					return Integer.parseInt(num);
				}
			}
		} catch (Exception ex) {
			System.err.println("Get data error!");
			System.err.println("Error message: " + ex.toString());
		}
		return 0;
	}

	/** method load setup file */
	public boolean load() {
		File file = new File(this.fileName);
		if (file.exists()) {
			try {
				ObjectInputStream ois = new ObjectInputStream(new FileInputStream(this.fileName));
				this.config = (HashMap<String, String>) ois.readObject();
				ois.close();

				if (!this.config.isEmpty()) {
					return true;
				}
			} catch (Exception ex) {
				System.err.println("Read date error!");
				System.err.println("Error message: " + ex.toString());
			}
		}
		return false;
	}

	/** method save setup file */
	public boolean save() {
		try {
			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(this.fileName));
			oos.writeObject(this.config);
			oos.close();
			return true;

		} catch (Exception ex) {
			System.err.println("Write date error!");
			System.err.println("Error message: " + ex.toString());
		}
		return false;
	}
}
